package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"scanner/src/config"
	"strings"
	"time"
)

var Token = ""

func PostMetrics(conf config.Conf, target string, isalive bool) {
	if len(Token) == 0 {
		if len(getToken(conf)) == 0 {
			fmt.Println("PostMetrics 获取token失败！！")
			return
		}
	}

	url := conf.Config.Url + "/g/gw/interface/performance/v2.0/data"
	method := "POST"
	reqbody := NetMetric{[]config.MetricContent{conf.Config.MetricContent.GetMetricContent(conf.Config, target, isalive)},
		time.Now().Format("20060102150405"),
	}

	jsonU, err := json.Marshal(reqbody)
	if err != nil {
		fmt.Println(err)
		return
	}
	payload := strings.NewReader(string(jsonU))

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Authorization", Token)
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))

}

func getToken(conf config.Conf) string {
	url := conf.Config.Url + "/g/gw/interface/addAccessToken"
	method := "POST"
	reqbody := AppID{
		Content{conf.Config.AppID}, time.Now().Format("20060102150405"),
	}
	jsonU, _ := json.Marshal(reqbody)
	payload := strings.NewReader(string(jsonU))

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println("getToken err:", err)
		return ""
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer res.Body.Close()

	fmt.Println("getToken:", res.StatusCode)
	fmt.Println(res.Status) // 获取状态码对应的文案
	fmt.Println(res.Header) // 获取响应头

	resbody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	fmt.Println(string(resbody))

	var reqToken TokenResponse
	err1 := json.Unmarshal(resbody, &reqToken)
	if err1 != nil {
		fmt.Println(err1)
		return ""
	}
	Token = reqToken.Result.AccessToken
	return reqToken.Result.AccessToken
}
